package com.xinggq.common.context;

import org.springframework.core.env.Environment;

/**
 * 测试环境用户上下文提供者
 * 在测试环境下提供默认的用户信息
 * 
 * @author xinggq
 * @since 2025/1/20
 */
public class TestUserContextProvider implements UserContextProvider {

  private final Environment environment;

  public TestUserContextProvider(Environment environment) {
    this.environment = environment;
  }

  @Override
  public UserInfo getCurrentUser() {
    return UserInfo.createTestUser();
  }

  @Override
  public boolean hasCurrentUser() {
    return true;
  }

  @Override
  public int getPriority() {
    return 10;
  }

  @Override
  public boolean isApplicable() {
    if (environment == null) {
      // 如果环境对象未设置，通过系统属性判断
      String activeProfiles = System.getProperty("spring.profiles.active");
      if (activeProfiles == null) {
        activeProfiles = System.getenv("SPRING_PROFILES_ACTIVE");
      }
      return activeProfiles != null && activeProfiles.contains("test");
    }
    
    String[] activeProfiles = environment.getActiveProfiles();
    for (String profile : activeProfiles) {
      if ("test".equals(profile)) {
        return true;
      }
    }
    
    return false;
  }
}